package com.launcher;

import com.launcher.factory.SimpleRocketFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wouter
 *         Date: 4/8/13
 *         Time: 2:11 PM
 */
public class RocketLauncher implements Runnable 
{
    private static boolean run;
    private static List<Launch> launchesList = new ArrayList<Launch>();
    private static int amountToLaunch = 5;

    public RocketLauncher() {
        RocketLauncher.run = true;
    }

    @Override
    public void run() {
        Launch launch;
        Logger logger = new Logger();

        while(RocketLauncher.run) {
            try {
                if(getRandomNumberBetween(0, 40) < 10) {
                    launch = new Launch();

                    SimpleRocketFactory rocketFactory = new SimpleRocketFactory();
                    Rocket rocket = rocketFactory.createRocket(RocketService.getInstance().getRandomPayLoad());
                    launch.setRocket(rocket);

                    launch.setDate(new Date());
                    
                    RocketService.getInstance().saveRocket(rocket);
                    RocketService.getInstance().saveLaunch(launch);
                    RocketLauncher.launchesList.add(launch);

                    logger.highLevelPrint("Launch!");
                }
                else {
                    logger.normalLevelPrint("No Launch!");
                }

                    Thread.sleep(700);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        launchesList.clear();
        Application.setEnabled(true);
    }

    private int getRandomNumberBetween(int start, int end) {
        if(start > end) {
            throw new IllegalArgumentException("Start can't exceed end");
        }

        return start + (int) (Math.random() * (end - start));
    }

    public static void stopLaunches() {
        RocketLauncher.run = false;
    }
    
    public static List<Launch> getLaunches()
    {
    	return RocketLauncher.launchesList;
    }
    
    public static void setAmountToLaunch(int n)
    {
    	amountToLaunch = n;
    }
    
    public static int getAmountToLaunch()
    {
    	return amountToLaunch;
    }
}
